package com.cdn.clock.component.lock;

import com.cdn.clock.component.LockComponent;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author 蔡定努
 * 2024/06/04 10:35
 */
public class RedissionLockComponent implements LockComponent {

    private RedissonClient redissonClient;

    public RedissonClient getRedissonClient() {
        return redissonClient;
    }

    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public boolean lock(String lockKey, long waitTime, long leaseTime, TimeUnit timeUnit) {
        try {
            RLock lock = redissonClient.getLock(lockKey);
            return lock.tryLock(waitTime, leaseTime, timeUnit);
        } catch (InterruptedException e) {
            return false;
        }
    }

    public boolean lock(String lockKey, long leaseTime, TimeUnit timeUnit) {
        try {
            RLock lock = redissonClient.getLock(lockKey);
            return lock.tryLock(-1,leaseTime, timeUnit);
        } catch (InterruptedException e) {
            return false;
        }
    }

    public boolean lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return true;
    }


    /**
     * @param lockKey key
     * @return boolean
     */
    @Override
    public boolean unLock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isLocked()) {
            lock.unlock();
        }
        return true;
    }


    /**
     * @param lockKey key
     * @return boolean
     */
    public boolean forceUnlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        return lock.forceUnlock();
    }


}
